package com.xinnet.mms.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xinnet.core.utils.page.PageView;
import com.xinnet.mms.allot.service.CustomAllotService;
import com.xinnet.mms.area.service.AreaService;
import com.xinnet.mms.customerManage.service.CustomerManageService;
import com.xinnet.mms.deployapproval.service.CustomDeployApprovalService;
import com.xinnet.mms.dept.service.DeptService;
import com.xinnet.mms.deptarea.service.DeptAreaService;
import com.xinnet.mms.empcustomrelation.service.EmpCustomRelationService;
import com.xinnet.mms.entity.Area;
import com.xinnet.mms.entity.CustomMixAudit;
import com.xinnet.mms.entity.Customer;
import com.xinnet.mms.entity.Dept;
import com.xinnet.mms.entity.Emp;
import com.xinnet.mms.entity.EmpCustomRelation;
import com.xinnet.mms.entity.Product;
import com.xinnet.mms.login.service.EmpService;

@Controller
@RequestMapping(value = "/ruleSet/customDeploy")
public class CustomDeployController {
	
	@Autowired
	private CustomerManageService customerManageService;
	@Autowired
	private EmpService empService;
	@Autowired
	private DeptService deptService;
	@Autowired
	private AreaService areaService;
	@Autowired
	private CustomAllotService customAllotService;
	@Autowired
	private DeptAreaService deptAreaService;
	@Autowired
	private EmpCustomRelationService empCustomRelationService;
	@Autowired
	private CustomDeployApprovalService customDeployApprovalService;
	
	ObjectMapper mapper = new ObjectMapper();
	/**
	 * 客户调配页面
	 * @param request
	 * @param response
	 * @return
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping(value = "/customDeployPage")
	public String customDeployPage(HttpServletRequest request,HttpServletResponse response){
		Emp currentUser = (Emp)request.getSession().getAttribute("currentUser");
		String deptId = currentUser.getId();
		String deptIdStr = deptService.getChildNodeId(deptId);
		//List<Customer> deployCustomList = customerManageService.getDeployCustomByDeptIdAndApplyerId(deptIdStr,applyerId);
		PageView pageView = new PageView();
		int pageSize = pageView.getPageSize();
		Map<String,Object> paramMap = new HashMap<String, Object>();
		String pageNow = request.getParameter("pageNow");
		paramMap.put("deptno", deptId);
		Integer limitTop=0;
		Integer limitDown=pageSize;
		if(pageNow==null || "".equals(pageNow)){
			limitTop=0;
		}else{
			limitTop=Integer.parseInt(pageNow)*pageSize-pageSize;
		}
		paramMap.put("limitTop", limitTop);
		paramMap.put("limitDown", limitDown);
		List<Customer> deployCustomList = customerManageService.getDeployCustomByMap(paramMap);
		
		Integer count = customerManageService.getDeployCustomCountByMap(paramMap);
		
		pageView.setPageSize(pageSize);
		if(pageNow==null || "".equals(pageNow)){
			pageView.setPageNow(1);
		}else{
			pageView.setPageNow(Integer.parseInt(pageNow));
		}if(count==null){
			count=0;
		}
		Integer pageCount=count%pageSize;
		pageView.setPageCount(pageCount);
		pageView.setRowCount(count);
		pageView.setQueryResult(count, deployCustomList);
		String deptJson  = "["+deptService.getDeptTreeByDeptId(deptId)+"]";
		List<Emp> empList = empService.getEmpListByDeptIdStr(deptIdStr);
		request.setAttribute("empList", empList);
		List<Area> areaList = deptAreaService.getAreaByDeptId(deptId);
		request.setAttribute("areaList", areaList);
		request.setAttribute("deptJson", deptJson);
		request.setAttribute("pageView", pageView);
		request.setAttribute("isQuery", false);
		return "/ruleSet/customDeploy";
	}
	/**
	 * 根据部门id获取员工列表
	 * @param request
	 * @param response
	 * @return
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@ResponseBody
	@RequestMapping(value = "/getEmpByDeptId")
	public List<Emp> getEmpByDeptId(HttpServletRequest request,HttpServletResponse response){
		String deptId = request.getParameter("deptId");
		String currentEmpId = request.getParameter("currentEmpId");
		List<Emp> resultEmpList = new ArrayList<Emp>();
		List<Emp> empList = empService.getEmpListExceptDeptLeader(deptId);

		if(empList!=null && empList.size()>0){
			for (int i = 0; i < empList.size(); i++) {
				Emp emp = empList.get(i);
				String tempEmpNo =  emp.getEmpno();
				if(!tempEmpNo.equals(currentEmpId)){
					resultEmpList.add(emp);
				}
			}
		}
		return resultEmpList;
	}
	/**
	 * 客户调配
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping(value = "/customDeploy")
	public String customDeploy(HttpServletRequest request,HttpServletResponse response) throws Exception{
		Emp currentUser = (Emp)request.getSession().getAttribute("currentUser");
		String applyId = currentUser.getEmpno();
		String updateEname = currentUser.getEname();
		String ecrId = request.getParameter("ecrId");
		String cusId = request.getParameter("cusId");
		String cName = request.getParameter("cName");
		String email = request.getParameter("email");
		String phone = request.getParameter("phone");
		String productId = request.getParameter("productId");
		String productCode = request.getParameter("productCode");
		
		String currentDeptNo = request.getParameter("currentDeptNo");
		String currentEmpNo = request.getParameter("currentEmpNo");
		//String currentDeptName = request.getParameter("currentDeptName");
		
		Dept currentDept = deptService.getDeptByDeptId(currentDeptNo);
		String currentDeptName = "";
		if(currentDept!=null){
			currentDeptName = currentDept.getDname();
		}
		String currentEmpName = request.getParameter("currentEmpName");
		String deployDeptName = request.getParameter("deployDeptName");
		String deployEmpName = request.getParameter("deployEmpName");
		String deployDeptId = request.getParameter("deployDeptId");
		String deployEmpNo = request.getParameter("deployEmpNo");
		/*if("".equals(deployEmpNo) || deployEmpNo==null ||"---请选择---".equals(deployEmpNo)){
			//return "3";
			deployEmpNo="*";
		}*/
		//Emp deployEmp = empService.getEmpbyEmpno(deployEmpNo);
		/*if(deployEmp==null){
			return "3";
		}*/
		/*if(deployEmp.getIsArtificialPush()!=1) {
			return "4";
		}*/
		String reason = request.getParameter("reason");
		CustomMixAudit customMixAudit = new CustomMixAudit();
		customMixAudit.setCusId(cusId);
		customMixAudit.setCname(cName);
		customMixAudit.setEmail(email);
		customMixAudit.setPhone(phone);
		customMixAudit.setIsEffect("2");
		customMixAudit.setUpdateEname(updateEname);
		customMixAudit.setMixCause(reason);
		customMixAudit.setFromEmpId(currentEmpNo);
		customMixAudit.setToEmpId(deployEmpNo);
		customMixAudit.setFromEmpName(currentEmpName);
		customMixAudit.setEcrId(ecrId);
		customMixAudit.setApplyerId(applyId);
		customMixAudit.setProductCode(productCode);
		customMixAudit.setProductId(productId);
		java.text.SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String updateTime = sdf.format(new Date());
		customMixAudit.setUpdateTime(updateTime);
		String id = UUID.randomUUID().toString();
		customMixAudit.setId(id);
		if(deployEmpNo==null || "".equals(deployEmpNo)){
			deployEmpNo="*";
		}
		String operationContent="从"+currentDeptName+"  "+currentEmpName+" 调配到  "+deployDeptName+" "+deployEmpName+","+
									currentDeptNo+"_"+currentEmpNo+"_"+deployDeptId+"_"+deployEmpNo;
		customMixAudit.setOperationContent(operationContent);
		customerManageService.addCustomMixAudit(customMixAudit);
		int result = customDeployApprovalService.approval(id,"1",applyId,currentUser.getId(),productId, productCode);
		return result+"";
		
		//return "redirect:/ruleSet/customDeploy/customDeployPage";
		
	}
	
	/**
	 * 根据条件查询要调配的客户
	 * @param request
	 * @param response
	 * @return
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/getCustomer")
	public String getCustomer(HttpServletRequest request,HttpServletResponse response){
		Emp currentUser = (Emp)request.getSession().getAttribute("currentUser");
		String deptId = currentUser.getId();
		String applyerId = currentUser.getEmpno();
		String customerId = request.getParameter("customerId");
		String contact = request.getParameter("contact");
		String phone = request.getParameter("phone");
		String email = request.getParameter("email");
		String empName = request.getParameter("empName");
		String area = request.getParameter("area");	
		String queryDeptId = request.getParameter("queryDeptId");
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("customerId", customerId);
		param.put("contact", contact);
		param.put("phone", phone);
		param.put("email", email);
		param.put("empName", empName);
		param.put("area", area);
		
		param.put("applyerId", applyerId);
		
		PageView pageView = new PageView();
		int pageSize = pageView.getPageSize();
		if("".equals(queryDeptId)){
			String deptIdStr = deptService.getChildNodeId(deptId);
			param.put("deptno", deptId);
			List<Emp> empList = empService.getEmpListByDeptIdStr(deptIdStr);
			request.setAttribute("empList", empList);
			List<Area> areaList = deptAreaService.getAreaByDeptId(deptId);
			request.setAttribute("areaList", areaList);
		}else{
			String deptIdStr = deptService.getChildNodeId(queryDeptId);
			param.put("deptno", deptId);
			Dept dept = deptService.getDeptByDeptId(queryDeptId);
			request.setAttribute("dept", dept);
			List<Emp> empList = empService.getEmpListByDeptIdStr(deptIdStr);
			request.setAttribute("empList", empList);
			List<Area> areaList = deptAreaService.getAreaByDeptId(queryDeptId);
			request.setAttribute("areaList", areaList);
		}
		String pageNow = request.getParameter("pageNow");
		Integer limitTop=0;
		Integer limitDown=pageSize;
		if(pageNow==null || "".equals(pageNow)){
			limitTop=0;
		}else{
			limitTop=Integer.parseInt(pageNow)*pageSize-pageSize;
		}
		param.put("limitTop", limitTop);
		param.put("limitDown", limitDown);
		Integer count =customerManageService.getDeployCustomCountByParam(param);
		List<Customer> deployCustomList = customerManageService.getDeployCustomByParam(param);

		pageView.setPageSize(pageSize);
		if(pageNow==null || "".equals(pageNow)){
			pageView.setPageNow(1);
		}else{
			pageView.setPageNow(Integer.parseInt(pageNow));
		}if(count==null){
			count=0;
		}
		Integer pageCount=count%pageSize;
		pageView.setPageCount(pageCount);
		pageView.setRowCount(count);
		pageView.setQueryResult(count, deployCustomList);

		request.setAttribute("isQuery", true);
		request.setAttribute("pageView", pageView);
	
		//String deptJson  = deptService.getDeptTree();
		String deptJson  = "["+deptService.getDeptTreeByDeptId(deptId)+"]";
        request.setAttribute("deptJson", deptJson);
		request.setAttribute("customerId",customerId);
		request.setAttribute("contact",contact);
		request.setAttribute("phone",phone);
		request.setAttribute("email",email);
        if(empName!=null && !"".equals(empName)){
        	 request.setAttribute("empName", empName);
        }
        if(area!=null && !"".equals(area)){
        	 request.setAttribute("areaName",area);
        }
		return "/ruleSet/customDeploy";	
	}
	
	/**
	 * 根据条件查询要调配的客户
	 * @param request
	 * @param response
	 * @return
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/getCustomerForAllDeploy")
	public void getCustomerForAllDeploy(HttpServletRequest request,HttpServletResponse response){
		Emp currentUser = (Emp)request.getSession().getAttribute("currentUser");
		String deptId = currentUser.getId();
		String applyerId = currentUser.getEmpno();
		String customerId = request.getParameter("customerId");
		String contact = request.getParameter("contact");
		String phone = request.getParameter("phone");
		String email = request.getParameter("email");
		String empName = request.getParameter("empName");
		String area = request.getParameter("area");	
		String queryDeptId = request.getParameter("queryDeptId");
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("customerId", customerId);
		param.put("contact", contact);
		param.put("phone", phone);
		param.put("email", email);
		param.put("empName", empName);
		param.put("area", area);
		PrintWriter pw = null;
		try {
			pw = response.getWriter();
		
			param.put("applyerId", applyerId);
			
			PageView pageView = new PageView();
			int pageSize = pageView.getPageSize();
			if("".equals(queryDeptId)){
				String deptIdStr = deptService.getChildNodeId(deptId);
				param.put("deptno", deptId);
				List<Emp> empList = empService.getEmpListByDeptIdStr(deptIdStr);
				request.setAttribute("empList", empList);
				List<Area> areaList = deptAreaService.getAreaByDeptId(deptId);
				request.setAttribute("areaList", areaList);
			}else{
				String deptIdStr = deptService.getChildNodeId(queryDeptId);
				param.put("deptno", deptId);
				Dept dept = deptService.getDeptByDeptId(queryDeptId);
				request.setAttribute("dept", dept);
				List<Emp> empList = empService.getEmpListByDeptIdStr(deptIdStr);
				request.setAttribute("empList", empList);
				List<Area> areaList = deptAreaService.getAreaByDeptId(queryDeptId);
				request.setAttribute("areaList", areaList);
			}
			String pageNow = request.getParameter("pageNow");
			Integer limitTop=0;
			Integer limitDown=pageSize;
			if(pageNow==null || "".equals(pageNow)){
				limitTop=0;
			}else{
				limitTop=Integer.parseInt(pageNow)*pageSize-pageSize;
			}
			param.put("limitTop", limitTop);
			param.put("limitDown", limitDown);
			
			List<Customer> deployCustomList = customerManageService.getDeployCustomByParam(param);
	
			request.setAttribute("isQuery", true);
			request.setAttribute("pageView", pageView);
			String customerListStr = mapper.writeValueAsString(deployCustomList);
			pw.println(customerListStr);
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}
	
	
	
	/**
	 * 批量调配客户
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=false)
	@RequestMapping(value = "/bathCustomDeploy")
	public String bathCustomDeploy(HttpServletRequest request,HttpServletResponse response) throws Exception {
		Emp currentUser = (Emp)request.getSession().getAttribute("currentUser");
		String applyerId = currentUser.getEmpno();
		String updateEname = currentUser.getEname();
		String ecrIdStr = request.getParameter("ecrIdStr");
		String[] ecrIdArray = ecrIdStr.split(",");
		
		String deployDeptName = request.getParameter("deployDeptName");
		String deployEmpName = request.getParameter("deployEmpName");
		String deployDeptId = request.getParameter("deployDeptId");
		String deployEmpNo = request.getParameter("deployEmpNo");
		String reason = request.getParameter("reason");
		
		String productCode = "";
		String productId = "";
		List<EmpCustomRelation> empCustomRelationList = empCustomRelationService.getEmpCustomRelationByIdStr(ecrIdStr);
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < ecrIdArray.length; i++) {
			String currentDeptNo = "";
			String currentDeptName = "";
			String currentEmpNo = "";
			String currentEmpName = "";
			String cName = "";
			String email = "";
			String phone = "";
			String ecrId =  ecrIdArray[i];
			CustomMixAudit customMixAudit = new CustomMixAudit();
			String id = UUID.randomUUID().toString();
			customMixAudit.setId(id);
			for (Iterator<EmpCustomRelation> iterator = empCustomRelationList.iterator(); iterator.hasNext();) {
				EmpCustomRelation empCustomRelation = (EmpCustomRelation) iterator.next();
				String tempEcrId =   empCustomRelation.getId();
				if(ecrId.equals(tempEcrId)){
					String customId = empCustomRelation.getCustomId();
					currentEmpNo = empCustomRelation.getEmpId();
					customMixAudit.setCusId(customId);
					currentDeptNo = empCustomRelation.getEmpDeptId();
					Dept currentDept = deptService.getDeptByDeptId(currentDeptNo);
					
					if(currentDept==null){
						currentDeptName="";
					} else {
						currentDeptName = currentDept.getDname();
					}
					currentEmpName = empCustomRelation.getEmpName();
					cName = empCustomRelation.getcName();
					email= empCustomRelation.getEmail();
					phone = empCustomRelation.getPhone();
					productCode = empCustomRelation.getProductCode();
					productId = empCustomRelation.getProductId();
					break;
				}

			}
			customMixAudit.setFromEmpId(currentEmpNo);
			customMixAudit.setToEmpId(deployEmpNo);
			customMixAudit.setEcrId(ecrId);
			customMixAudit.setCname(cName);
			customMixAudit.setEmail(email);
			customMixAudit.setPhone(phone);
			customMixAudit.setIsEffect("2");
			customMixAudit.setUpdateEname(updateEname);
			customMixAudit.setMixCause(reason);
			customMixAudit.setProductCode(productCode);
			customMixAudit.setProductId(productId);
			java.text.SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String updateTime = sdf.format(new Date());
			customMixAudit.setUpdateTime(updateTime);
			customMixAudit.setApplyerId(applyerId);
			if(deployEmpNo==null || "".equals(deployEmpNo)){
				deployEmpNo="*";
			}
			String operationContent="从"+currentDeptName+"  "+currentEmpName+" 调配到  "+deployDeptName+" "+deployEmpName+","+
										currentDeptNo+"_"+currentEmpNo+"_"+deployDeptId+"_"+deployEmpNo;
			customMixAudit.setOperationContent(operationContent);
			System.out.println(ecrId+"--"+phone);
			try {
				customerManageService.addCustomMixAudit(customMixAudit);
			} catch (Exception e) {
				System.out.println(ecrId+"--"+phone);
				e.printStackTrace();
			}
			sb.append(id).append(",");
			
		}
		sb.deleteCharAt(sb.length()-1);
		int result = customDeployApprovalService.bathApproval(sb.toString(),"1",applyerId,currentUser.getId());
		return result+"";
		//return "redirect:/ruleSet/customDeploy/customDeployPage";
	}
	
	
	/**
	 * 检测是否可以调配
	 * @param request
	 * @param response
	 * @return
	 * @throws SQLException 
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@ResponseBody
	@RequestMapping(value = "/checkIsCanDeploy")
	public String checkIsCanDeploy(HttpServletRequest request,HttpServletResponse response) throws SQLException{
		String deployDeptId = request.getParameter("deployDeptId");
		Product product = customAllotService.getProductByDeptno(deployDeptId);
		if(product==null){
			return "false";
		}
		return "true";
	}
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@ResponseBody
	@RequestMapping(value = "/getEmpAndAreaByDeptId")
	public void getEmpAndAreaByDeptId(HttpServletRequest request,HttpServletResponse response) throws IOException{
		response.setContentType("text/html;charset=UTF-8"); 
		response.setCharacterEncoding("UTF-8");
		String deptId = request.getParameter("deptId");
		String deptIdStr = deptService.getChildNodeId(deptId);
		Emp empParm = new Emp();
		//empParm.setId(deptId);
		empParm.setDeptIdStr(deptIdStr);
		Emp currentUser = (Emp)request.getSession().getAttribute("currentUser");
		String empno = currentUser.getEmpno();
		List<Emp> resultEmpList = new ArrayList<Emp>();
		List<Emp> empList = empService.getEmpList(empParm);
		if(empList!=null && empList.size()>0){
			for (int i = 0; i < empList.size(); i++) {
				Emp emp = empList.get(i);
				String tempEmpNo =  emp.getEmpno();
				if(!tempEmpNo.equals(empno)){
					resultEmpList.add(emp);
				}
			}
		}
		List<Area> areaList = deptAreaService.getAreaListByDeptIdStr(deptIdStr);
		Map<String, List<?>> map = new HashMap<String, List<?>>();
        map.put("empList",resultEmpList); 
        map.put("areaList",areaList); 
		JSONArray jsonArray = JSONArray.fromObject(map);
		PrintWriter printWriter=response.getWriter();
		printWriter.print(jsonArray.toString());
		return;
	}

}
